// API基础URL
const API_BASE = 'http://localhost:3000/api';

// 富文本编辑器实例
let editor = null;

// 初始化富文本编辑器
async function initEditor() {
    // 如果编辑器未加载，先加载它
    if (!window.wangEditor) {
        if (window.lazyLoadEditor) {
            await window.lazyLoadEditor();
        } else {
            console.error('编辑器加载函数未找到');
            return;
        }
    }
    
    if (window.wangEditor) {
        const { createEditor, createToolbar } = window.wangEditor;
        
        const editorConfig = {
            placeholder: '请输入文章内容...',
            onChange(editor) {
                const html = editor.getHtml();
                console.log('editor content', html);
                // 同步到 textarea
                document.getElementById('content').value = html;
            },
            MENU_CONF: {
                uploadImage: {
                    server: `${API_BASE}/upload`,
                    fieldName: 'file',
                    maxFileSize: 5 * 1024 * 1024, // 5MB
                    allowedFileTypes: ['image/jpeg', 'image/png', 'image/gif', 'image/webp'],
                    timeout: 10 * 1000, // 10秒超时
                    withCredentials: false,
                    customInsert: function(res, insertFn) {
                        if (res.success && res.data) {
                            insertFn(res.data.url, '', res.data.url);
                        } else {
                            alert('图片上传失败：' + (res.message || '未知错误'));
                        }
                    },
                    customError: function(xhr, editor) {
                        alert('上传失败，请检查网络连接或文件大小');
                    }
                }
            }
        };

        editor = createEditor({
            selector: '#editor-container',
            html: '<p><br></p>',
            config: editorConfig,
            mode: 'default'
        });

        const toolbarConfig = {};

        const toolbar = createToolbar({
            editor,
            selector: '#toolbar-container',
            config: toolbarConfig,
            mode: 'default'
        });
        
        console.log('富文本编辑器初始化成功');
    } else {
        console.error('wangEditor未加载，请检查依赖');
    }
}

// 通用API请求函数
async function apiRequest(url, options = {}) {
    try {
        const response = await fetch(url, {
            headers: {
                'Content-Type': 'application/json',
                ...options.headers
            },
            ...options
        });
        
        const data = await response.json();
        return data;
    } catch (error) {
        console.error('API请求失败：', error);
        alert('网络请求失败，请检查服务器是否运行');
        return { success: false, message: '网络请求失败' };
    }
}

// 博客管理相关函数
function showTab(tabName) {
    // 隐藏所有标签内容
    const tabContents = document.querySelectorAll('.tab-content');
    tabContents.forEach(content => content.classList.remove('active'));
    
    // 移除所有标签按钮的激活状态
    const tabBtns = document.querySelectorAll('.tab-btn');
    tabBtns.forEach(btn => btn.classList.remove('active'));
    
    // 显示选中的标签内容
    document.getElementById(tabName === 'all' ? 'all-articles' : tabName).classList.add('active');
    
    // 激活对应的标签按钮
    event.target.classList.add('active');
    
    // 加载对应标签的文章
    loadArticles(tabName);
}

// 加载文章列表
async function loadArticles(status = 'all') {
    const containerId = status === 'all' ? 'all-articles' : status;
    const container = document.getElementById(containerId);
    
    if (!container) return;
    
    const articleList = container.querySelector('.article-list');
    articleList.innerHTML = '<p>加载中...</p>';
    
    try {
        const queryParams = status === 'all' ? '' : `?status=${status}`;
        const result = await apiRequest(`${API_BASE}/articles${queryParams}`);
        
        if (result.success) {
            renderArticles(result.data, status);
        } else {
            articleList.innerHTML = '<p>加载失败：' + result.message + '</p>';
        }
    } catch (error) {
        articleList.innerHTML = '<p>加载失败，请检查服务器连接</p>';
    }
}

// 渲染文章列表
function renderArticles(articles, status) {
    const containerId = status === 'all' ? 'all-articles' : status;
    const container = document.getElementById(containerId);
    
    if (!container) return;
    
    const articleList = container.querySelector('.article-list');
    articleList.innerHTML = '';
    
    if (articles.length === 0) {
        articleList.innerHTML = '<p class="no-articles">暂无文章</p>';
        return;
    }
    
    articles.forEach(article => {
        const articleElement = createArticleElement(article, status);
        articleList.appendChild(articleElement);
    });
}

// 创建文章DOM元素
function createArticleElement(article, status) {
    const div = document.createElement('div');
    div.className = 'article-item';
    if (status === 'trash') div.classList.add('deleted');
    
    const categoryMap = {
        'technology': '技术',
        'life': '生活',
        'travel': '旅行'
    };
    
    const statusMap = {
        'published': '已发布',
        'draft': '草稿',
        'deleted': '已删除'
    };
    
    // 截取纯文本内容作为摘要
    const excerpt = article.content.replace(/<[^>]*>/g, '').substring(0, 100) + '...';
    
    div.innerHTML = `
        <h3>${article.title}</h3>
        <p class="article-meta">${categoryMap[article.category] || article.category} | ${article.createdAt} | ${statusMap[article.status] || article.status}</p>
        <p class="article-excerpt">${excerpt}</p>
        <div class="article-actions">
            ${status === 'all' ? `<button onclick="editArticle(${article.id})">编辑</button>
            <button onclick="deleteArticle(${article.id})">删除</button>` : ''}
            ${status === 'drafts' ? `<button onclick="editArticle(${article.id})">继续编辑</button>
            <button onclick="publishDraft(${article.id})">发布</button>
            <button onclick="deleteDraft(${article.id})">删除</button>` : ''}
            ${status === 'trash' ? `<button onclick="restoreArticle(${article.id})">恢复</button>
            <button onclick="permanentDelete(${article.id})">永久删除</button>` : ''}
        </div>
    `;
    
    return div;
}

function showCreateForm() {
    // 隐藏所有标签内容
    const tabContents = document.querySelectorAll('.tab-content');
    tabContents.forEach(content => content.classList.remove('active'));
    
    // 显示创作表单
    document.getElementById('create-form').style.display = 'block';
    
    // 初始化编辑器（如果尚未初始化）
    if (!editor) {
        setTimeout(() => {
            initEditor();
        }, 100);
    }
}

function cancelCreate() {
    // 隐藏创作表单
    document.getElementById('create-form').style.display = 'none';
    
    // 显示全部文章标签
    document.getElementById('all-articles').classList.add('active');
    
    // 重置表单
    document.getElementById('blogForm').reset();
    
    // 清空编辑器内容
    if (editor) {
        editor.clear();
    }
}

async function editArticle(id) {
    try {
        const result = await apiRequest(`${API_BASE}/articles/${id}`);
        
        if (result.success) {
            const article = result.data;
            
            // 填充表单
            document.getElementById('title').value = article.title;
            document.getElementById('category').value = article.category;
            document.getElementById('theme').value = article.theme;
            document.getElementById('keywords').value = article.keywords;
            
            // 设置编辑器内容
            if (editor) {
                editor.setHtml(article.content);
            }
            
            // 显示编辑表单
            showCreateForm();
            
            // 添加更新按钮
            const formActions = document.querySelector('.form-actions');
            formActions.innerHTML = `
                <button type="button" onclick="updateArticle(${id})">更新</button>
                <button type="button" onclick="cancelCreate()">取消</button>
            `;
        } else {
            alert('获取文章失败：' + result.message);
        }
    } catch (error) {
        alert('编辑文章失败');
    }
}

async function updateArticle(id) {
    const title = document.getElementById('title').value;
    const category = document.getElementById('category').value;
    const theme = document.getElementById('theme').value;
    const keywords = document.getElementById('keywords').value;
    const content = document.getElementById('content').value;
    
    if (!title.trim() || !content.trim()) {
        alert('标题和内容不能为空');
        return;
    }
    
    try {
        const result = await apiRequest(`${API_BASE}/articles/${id}`, {
            method: 'PUT',
            body: JSON.stringify({
                title,
                category,
                theme,
                keywords,
                content
            })
        });
        
        if (result.success) {
            alert('文章更新成功');
            cancelCreate();
            loadArticles('all');
        } else {
            alert('更新失败：' + result.message);
        }
    } catch (error) {
        alert('更新文章失败');
    }
}

async function deleteArticle(id) {
    if (confirm('确定要删除这篇文章吗？')) {
        try {
            const result = await apiRequest(`${API_BASE}/articles/${id}`, {
                method: 'DELETE'
            });
            
            if (result.success) {
                alert('文章已移至回收站');
                loadArticles('all');
            } else {
                alert('删除失败：' + result.message);
            }
        } catch (error) {
            alert('删除文章失败');
        }
    }
}

async function deleteDraft(id) {
    if (confirm('确定要删除这个草稿吗？')) {
        try {
            const result = await apiRequest(`${API_BASE}/articles/${id}/permanent`, {
                method: 'DELETE'
            });
            
            if (result.success) {
                alert('草稿已删除');
                loadArticles('drafts');
            } else {
                alert('删除失败：' + result.message);
            }
        } catch (error) {
            alert('删除草稿失败');
        }
    }
}

async function publishDraft(id) {
    if (confirm('确定要发布这个草稿吗？')) {
        try {
            const result = await apiRequest(`${API_BASE}/articles/${id}`, {
                method: 'PUT',
                body: JSON.stringify({
                    status: 'published'
                })
            });
            
            if (result.success) {
                alert('草稿已发布');
                loadArticles('drafts');
            } else {
                alert('发布失败：' + result.message);
            }
        } catch (error) {
            alert('发布草稿失败');
        }
    }
}

async function restoreArticle(id) {
    if (confirm('确定要恢复这篇文章吗？')) {
        try {
            const result = await apiRequest(`${API_BASE}/articles/${id}/restore`, {
                method: 'PATCH'
            });
            
            if (result.success) {
                alert('文章已恢复');
                loadArticles('trash');
            } else {
                alert('恢复失败：' + result.message);
            }
        } catch (error) {
            alert('恢复文章失败');
        }
    }
}

async function permanentDelete(id) {
    if (confirm('确定要永久删除这篇文章吗？此操作不可恢复！')) {
        try {
            const result = await apiRequest(`${API_BASE}/articles/${id}/permanent`, {
                method: 'DELETE'
            });
            
            if (result.success) {
                alert('文章已永久删除');
                loadArticles('trash');
            } else {
                alert('删除失败：' + result.message);
            }
        } catch (error) {
            alert('永久删除失败');
        }
    }
}

async function saveDraft() {
    const title = document.getElementById('title').value;
    const content = document.getElementById('content').value;
    
    if (!title.trim()) {
        alert('请输入文章标题');
        return;
    }
    
    if (!content.trim()) {
        alert('请输入文章内容');
        return;
    }
    
    const category = document.getElementById('category').value;
    const theme = document.getElementById('theme').value;
    const keywords = document.getElementById('keywords').value;
    
    try {
        const result = await apiRequest(`${API_BASE}/articles`, {
            method: 'POST',
            body: JSON.stringify({
                title,
                category,
                theme,
                keywords,
                content,
                status: 'draft'
            })
        });
        
        if (result.success) {
            alert('草稿保存成功');
            cancelCreate();
            loadArticles('drafts');
        } else {
            alert('保存失败：' + result.message);
        }
    } catch (error) {
        alert('保存草稿失败');
    }
}

async function submitBlog() {
    const title = document.getElementById('title').value;
    const content = document.getElementById('content').value;
    
    if (!title.trim() || !content.trim()) {
        alert('标题和内容不能为空');
        return;
    }
    
    const category = document.getElementById('category').value;
    const theme = document.getElementById('theme').value;
    const keywords = document.getElementById('keywords').value;
    
    try {
        const result = await apiRequest(`${API_BASE}/articles`, {
            method: 'POST',
            body: JSON.stringify({
                title,
                category,
                theme,
                keywords,
                content,
                status: 'published'
            })
        });
        
        if (result.success) {
            alert('博客发布成功！');
            cancelCreate();
            loadArticles('all');
        } else {
            alert('发布失败：' + result.message);
        }
    } catch (error) {
        alert('发布博客失败');
    }
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    console.log('博客管理系统已加载');
    
    // 延迟初始化编辑器，确保DOM完全加载
    setTimeout(() => {
        if (document.getElementById('create-form').style.display !== 'none') {
            initEditor();
        }
    }, 500);
});